package com.ymy.thinking.in.spring.dependency.injection;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

/**
 * {@link ObjectFactory} {@link ObjectProvider} 延迟依赖注入示例
 *
 * @author Ringo
 * @date 2021/9/30 14:58
 * @see ObjectFactory
 * @see ObjectProvider
 */
public class LazyAnnotationDependencyInjectionDemo {

    @Autowired
    private User user;  // 实时注入

    @Autowired
    private ObjectProvider<User> userObjectProvider; // 延迟注入

    @Autowired
    private ObjectFactory<User> userObjectFactory;  // ObjectFactory 延迟注入

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext();
        applicationContext.register(LazyAnnotationDependencyInjectionDemo.class);
        applicationContext.refresh();

        LazyAnnotationDependencyInjectionDemo demo = applicationContext.getBean(LazyAnnotationDependencyInjectionDemo.class);
        System.out.println("demo.user = " + demo.user);
        System.out.println("demo.userObjectProvider = " + demo.userObjectProvider.getIfAvailable());
        System.out.println("demo.userObjectFactory = " + demo.userObjectFactory.getObject());

        System.out.println("ObjectProvider 输出所有的 Bean：");
        demo.userObjectProvider.forEach(System.out::println);

        applicationContext.close();
    }

    @Bean
    @Primary
    public User user1() {
        return new User("zs", 8);
    }

    @Bean
    public User user2() {
        return new User("ls", 9);
    }

}
